﻿using System;
using System.Net;
using ETHotfix;
using ETModel;

namespace ET.HelloWorld.Hotfix.Handlers {
    [MessageHandler(AppType.Gate)]
    public class C2G_ConnectHandler : AMRpcHandler<C2G_Connect, G2C_Connect> {
        protected override void Run(Session session, C2G_Connect message, Action<G2C_Connect> reply) {
            //抽象方法是同步的,需要操作异步代码,从这里转一手
            RunAsync(session, message, reply).Coroutine();
        }
        protected async ETVoid RunAsync(Session session, C2G_Connect message, Action<G2C_Connect> reply) {
            G2C_Connect response = new G2C_Connect();
            try {

                //!!! 连接上Gate服务器,必须调用本方法完成玩家的初始化!
                var gatePlayer = session.GatePlayerLoginSuccess(null);

                //接着连map服务器
                IPEndPoint mapAddress = StartConfigComponent.Instance.MapConfigs[0].GetComponent<InnerConfig>().IPEndPoint;//直接取配置里的第一个Map服务器配置了
                Session mapSession = Game.Scene.GetComponent<NetInnerComponent>().Get(mapAddress);
                M2G_EnterMap enterMapResult = (M2G_EnterMap)await mapSession.Call(new G2M_EnterMap() { GateSessionInstanceId = gatePlayer.InstanceId });
                if ((response.Error = enterMapResult.Error) != 0) {
                    response.Message = enterMapResult.Message;
                    reply(response);
                    return;
                }

                //!!! 用户从Gate连到Map成功后,必须调用初始化
                session.GatePlayerLoginMapSuccess(enterMapResult.MapPlayerInstanceId);

                response.Units.Add(enterMapResult.Units);
                response.SelfUnitIds.Add(enterMapResult.SelfUnitIds);

                response.PlayerId = gatePlayer.Id;

                //调试信息
                response.AllGizmosMeshs.Add(enterMapResult.AllGizmosMeshs);
                response.AllRayTestLine.Add(enterMapResult.AllRayTestLine);

                reply(response);
            } catch (Exception e) {
                ReplyError(response, e, reply);
            }
        }
    }
}